package org.ISCS.service.buildimpl;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.command.BuildImageResultCallback;
import com.github.dockerjava.api.model.BuildResponseItem;
import com.github.dockerjava.core.DefaultDockerClientConfig;
import com.github.dockerjava.core.DockerClientBuilder;
import org.ISCS.entity.Dockerimage;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Arrays;
import java.util.HashSet;

@Service
public class DockerService {

    public void buildDockerImage(String dockerfilePath, Dockerimage dockerImage,String imageName) {
        DefaultDockerClientConfig config = DefaultDockerClientConfig.createDefaultConfigBuilder().build();
        DockerClient dockerClient = DockerClientBuilder.getInstance(config).build();
        try {
            File dockerfile = new File(dockerfilePath);
            File baseDir = dockerfile.getParentFile();

            String imageId = dockerClient.buildImageCmd(baseDir)
                    .withDockerfile(dockerfile)
                    .withTags(new HashSet<>(Arrays.asList(imageName)))
                    .exec(new BuildImageResultCallback() {
                        @Override
                        public void onNext(BuildResponseItem item) {
                            super.onNext(item);
                            if (item.getStream() != null) {
                                System.out.println(item.getStream());
                            }
                        }
                    })
                    .awaitImageId();
            if (imageId != null) {
                dockerImage.setDockerImageStatus(1);
            } else {
                dockerImage.setDockerImageStatus(2);
            }
        } catch (Exception e) {
            dockerImage.setDockerImageStatus(2);
            e.printStackTrace();
        }
    }



}